#ifndef DATA_MANAGER_H
#define DATA_MANAGER_H

#include <stdint.h>
#include <stdbool.h>
#include <stdatomic.h>
#include <time.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "ui.h"
#include "lvgl/lvgl.h"

// 行驶数据结构体定义
typedef struct {
    uint32_t driving_distance;    // 行驶里程(km)
    uint32_t total_distance;      // 总里程(km)
    uint32_t driving_time;        // 行驶时间(min)
    float fuel_consumption;       // 油耗(L/100km)
    time_t last_update;           // 最后更新时间
    bool is_initialized;          // 初始化状态标志
} DrivingData;

// 系统状态结构体定义
typedef struct SystemState {
    DrivingData current_data;
    DrivingData backup_data;
    time_t last_update;
    bool data_modified;
    pthread_mutex_t data_mutex;
} SystemState;

extern SystemState system_state;

// 日志级别定义
typedef enum {
    LOG_DEBUG,
    LOG_INFO,
    LOG_WARNING,
    LOG_ERROR,
    LOG_WARN = LOG_WARNING  // 为兼容性添加
} LogLevel;

// 日志函数声明
void log_message(LogLevel level, const char *format, ...);

extern atomic_bool data_generation_in_progress;

static inline bool lock_data(void) {
    int lock_result = pthread_mutex_lock(&system_state.data_mutex);
    if (lock_result != 0) {
        log_message(LOG_ERROR, "Lock failed at %s:%d (error: %d)", __FILE__, __LINE__, lock_result);
    }
    return lock_result == 0;
}
#define LOCK_DATA() lock_data()

#define UNLOCK_DATA() do { \
    if (pthread_mutex_unlock(&system_state.data_mutex) != 0) { \
        log_message(LOG_ERROR, "Unlock failed at %s:%d", __FILE__, __LINE__); \
    } \
} while(0)

// 数据范围定义
#define MIN_DISTANCE 500
#define MAX_DISTANCE 9999
#define MIN_TIME 1
#define MAX_TIME 99
#define MIN_FUEL 1.0f
#define MAX_FUEL 99.0f
#define MIN_TOTAL_DISTANCE 1000
#define MAX_TOTAL_DISTANCE 99999

// 数学计算宏
#define CLAMP(x, min, max) ((x) < (min) ? (min) : ((x) > (max) ? (max) : (x)))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))

// 数据管理函数声明
SystemState* get_system_state(void);
bool generate_driving_data(void);
bool init_driving_data(void);
void data_manager_init(void);
bool reset_driving_data(void);
bool save_driving_data(bool lock);
DrivingData get_current_driving_data(void);
void update_driving_data(uint32_t distance_delta, uint32_t time_delta, float fuel_delta);

// 数据验证函数声明
bool validate_driving_data(const DrivingData *data);
void sanitize_driving_data(DrivingData *data); // 数据修正函数

#endif // DATA_MANAGER_H